<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>预约回收 - 废物回收管理系统</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://cdn.bootcdn.net/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css" rel="stylesheet">
    <!-- 百度地图API -->
    <script type="text/javascript" th:src="@{'https://api.map.baidu.com/api?v=3.0&type=webgl&ak=' + ${@baiduMapConfig.apiKey}}"></script>
    <script src="/js/baidu-map.js"></script>
    <style>
        body {
            background-color: #f8f9fa;
        }
        .form-container {
            max-width: 1000px;
            margin: 2rem auto;
            background: white;
            padding: 2rem;
            border-radius: 15px;
            box-shadow: 0 0 20px rgba(0,0,0,0.1);
        }
        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin-bottom: 3rem;
            position: relative;
        }
        .step-indicator::before {
            content: '';
            position: absolute;
            top: 25px;
            left: 0;
            right: 0;
            height: 2px;
            background: #e9ecef;
            z-index: 1;
        }
        .step {
            text-align: center;
            position: relative;
            z-index: 2;
            background: white;
            padding: 0 1rem;
        }
        .step-number {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: #e9ecef;
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 0.5rem;
            color: #6c757d;
            font-weight: bold;
        }
        .step.active .step-number {
            background: #0d6efd;
            color: white;
        }
        .step.completed .step-number {
            background: #198754;
            color: white;
        }
        .waste-type-card {
            cursor: pointer;
            transition: all 0.3s ease;
            height: 100%;
        }
        .waste-type-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .waste-type-card.selected {
            border-color: #0d6efd;
            background-color: #f8f9fa;
        }
        .waste-icon {
            font-size: 2rem;
            margin-bottom: 1rem;
            color: #0d6efd;
        }
        .time-slot {
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .time-slot:hover {
            transform: translateY(-3px);
            box-shadow: 0 3px 10px rgba(0,0,0,0.1);
        }
        .time-slot.selected {
            border-color: #0d6efd;
            background-color: #f8f9fa;
        }
        .map-container {
            height: 400px;
            border: 1px solid #ddd;
            border-radius: 8px;
            overflow: hidden;
            margin-bottom: 15px;
            box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        }
        .form-group label {
            font-weight: 500;
            margin-bottom: 0.5rem;
            color: #495057;
        }
        .form-control {
            border-radius: 6px;
            border: 1px solid #ced4da;
            padding: 0.5rem 0.75rem;
        }
        .form-control:focus {
            border-color: #80bdff;
            box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
        }
        .btn-outline-primary {
            border-color: #0d6efd;
            color: #0d6efd;
        }
        .btn-outline-primary:hover {
            background-color: #0d6efd;
            color: white;
        }
        .form-text {
            font-size: 0.875rem;
            color: #6c757d;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark bg-primary">
        <div class="container">
            <a class="navbar-brand" href="/resident">
                <i class="fas fa-recycle me-2"></i>废物回收管理系统
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/resident">首页</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/orders/create">预约回收</a>
                    </li>
                </ul>
            </div>
        </div>
    </nav>

    <div class="container">
        <div class="form-container">
            <!-- 步骤指示器 -->
            <div class="step-indicator">
                <div class="step active" id="step1">
                    <div class="step-number">1</div>
                    <div class="step-title">选择地址</div>
                </div>
                <div class="step" id="step2">
                    <div class="step-number">2</div>
                    <div class="step-title">物品信息</div>
                </div>
                <div class="step" id="step3">
                    <div class="step-number">3</div>
                    <div class="step-title">预约时间</div>
                </div>
                <div class="step" id="step4">
                    <div class="step-number">4</div>
                    <div class="step-title">确认信息</div>
                </div>
            </div>

            <!-- 表单内容 -->
            <form id="orderForm" onsubmit="return submitOrder(event)">
                <!-- 步骤1：选择地址 -->
                <div class="step-content" id="step1-content">
                    <div class="form-group">
                        <label for="savedAddress">选择回收地址</label>
                        <select class="form-control mb-3" id="savedAddress" onchange="loadSavedAddress(this.value)">
                            <option value="">选择已保存的地址</option>
                            <option th:each="address : ${savedAddresses}" 
                                    th:value="${address.id}" 
                                    th:text="${address.address}"></option>
                        </select>

                        <div class="input-group mb-3">
                            <input type="text" class="form-control" id="searchAddress" 
                                   placeholder="请输入地址搜索或点击地图选择位置">
                            <div class="input-group-append">
                                <button class="btn btn-outline-secondary" type="button" 
                                        onclick="searchLocation()">
                                    <i class="fas fa-search"></i> 搜索
                                </button>
                            </div>
                        </div>

                        <div id="mapContainer" class="map-container"></div>

                        <div class="form-group mb-3">
                            <label for="detailAddress">详细地址</label>
                            <input type="text" class="form-control" id="detailAddress" name="address" 
                                   placeholder="请输入详细地址" required>
                        </div>

                        <div class="form-group mb-3">
                            <label for="contactName">联系人</label>
                            <input type="text" class="form-control" id="contactName" name="contactName" 
                                   placeholder="请输入联系人姓名" required>
                        </div>

                        <div class="form-group mb-3">
                            <label for="contactPhone">联系电话</label>
                            <input type="tel" class="form-control" id="contactPhone" name="contactPhone" 
                                   placeholder="请输入联系电话" required>
                        </div>

                        <div class="form-check mb-3">
                            <input type="checkbox" class="form-check-input" id="saveAddress" name="saveAddress">
                            <label class="form-check-label" for="saveAddress">保存为常用地址</label>
                        </div>

                        <input type="hidden" id="latitude" name="latitude">
                        <input type="hidden" id="longitude" name="longitude">
                    </div>
                    
                    <div class="text-end mt-3">
                        <button type="button" class="btn btn-primary" onclick="nextStep(1)">下一步</button>
                    </div>
                </div>

                <!-- 步骤2：物品信息 -->
                <div class="step-content" id="step2-content" style="display: none;">
                    <div class="mb-4">
                        <label class="form-label">选择回收物品类型</label>
                        <div class="row">
                            <div class="col-md-3 mb-3">
                                <div class="card waste-type-card" onclick="selectWasteType(this, 'PAPER')">
                                    <div class="card-body text-center">
                                        <i class="fas fa-newspaper fa-2x mb-2"></i>
                                        <h6 class="card-title">废纸</h6>
                                        <small class="text-muted">报纸、纸箱等</small>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 mb-3">
                                <div class="card waste-type-card" onclick="selectWasteType(this, 'PLASTIC')">
                                    <div class="card-body text-center">
                                        <i class="fas fa-wine-bottle fa-2x mb-2"></i>
                                        <h6 class="card-title">塑料</h6>
                                        <small class="text-muted">饮料瓶、包装袋等</small>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 mb-3">
                                <div class="card waste-type-card" onclick="selectWasteType(this, 'METAL')">
                                    <div class="card-body text-center">
                                        <i class="fas fa-cog fa-2x mb-2"></i>
                                        <h6 class="card-title">金属</h6>
                                        <small class="text-muted">易拉罐、废铁等</small>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 mb-3">
                                <div class="card waste-type-card" onclick="selectWasteType(this, 'APPLIANCE')">
                                    <div class="card-body text-center">
                                        <i class="fas fa-tv fa-2x mb-2"></i>
                                        <h6 class="card-title">电器</h6>
                                        <small class="text-muted">废旧家电、电子产品</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label for="estimatedWeight" class="form-label">预估重量（kg）</label>
                        <input type="number" class="form-control" id="estimatedWeight" name="estimatedWeight" min="0.1" step="0.1" required>
                    </div>
                    <div class="text-end">
                        <button type="button" class="btn btn-secondary me-2" onclick="prevStep(2)">上一步</button>
                        <button type="button" class="btn btn-primary" onclick="nextStep(2)">下一步</button>
                    </div>
                </div>

                <!-- 步骤3：预约时间 -->
                <div class="step-content" id="step3-content" style="display: none;">
                    <div class="mb-3">
                        <label class="form-label">选择预约日期</label>
                        <input type="text" class="form-control" id="appointmentDate" name="appointmentDate" readonly>
                    </div>
                    <div class="mb-4">
                        <label class="form-label">选择预约时间段</label>
                        <div class="row">
                            <div class="col-md-3 mb-3">
                                <div class="card time-slot text-center" data-time="09:00-11:00" onclick="selectTimeSlot(this)">
                                    <div class="card-body">
                                        <i class="fas fa-clock"></i>
                                        <h6 class="card-title">上午</h6>
                                        <small>09:00-11:00</small>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 mb-3">
                                <div class="card time-slot text-center" data-time="11:00-13:00" onclick="selectTimeSlot(this)">
                                    <div class="card-body">
                                        <i class="fas fa-clock"></i>
                                        <h6 class="card-title">中午</h6>
                                        <small>11:00-13:00</small>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 mb-3">
                                <div class="card time-slot text-center" data-time="13:00-15:00" onclick="selectTimeSlot(this)">
                                    <div class="card-body">
                                        <i class="fas fa-clock"></i>
                                        <h6 class="card-title">下午</h6>
                                        <small>13:00-15:00</small>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 mb-3">
                                <div class="card time-slot text-center" data-time="15:00-17:00" onclick="selectTimeSlot(this)">
                                    <div class="card-body">
                                        <i class="fas fa-clock"></i>
                                        <h6 class="card-title">傍晚</h6>
                                        <small>15:00-17:00</small>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="text-end">
                        <button type="button" class="btn btn-secondary me-2" onclick="prevStep(3)">上一步</button>
                        <button type="button" class="btn btn-primary" onclick="nextStep(3)">下一步</button>
                    </div>
                </div>

                <!-- 步骤4：确认信息 -->
                <div class="step-content" id="step4-content" style="display: none;">
                    <div class="card mb-3">
                        <div class="card-body">
                            <h5 class="card-title mb-4">预约信息确认</h5>
                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <strong>回收地址：</strong>
                                </div>
                                <div class="col-md-8" id="confirm-address"></div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <strong>联系人：</strong>
                                </div>
                                <div class="col-md-8" id="confirm-contact"></div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <strong>联系电话：</strong>
                                </div>
                                <div class="col-md-8" id="confirm-phone"></div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <strong>物品类型：</strong>
                                </div>
                                <div class="col-md-8" id="confirm-type"></div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <strong>预估重量：</strong>
                                </div>
                                <div class="col-md-8"><span id="confirm-weight"></span> kg</div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-4">
                                    <strong>预约时间：</strong>
                                </div>
                                <div class="col-md-8" id="confirm-time"></div>
                            </div>
                        </div>
                    </div>
                    <div class="text-end">
                        <button type="button" class="btn btn-secondary me-2" onclick="prevStep(4)">修改信息</button>
                        <button type="submit" class="btn btn-primary">提交预约</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/bootstrap-datepicker/1.9.0/locales/bootstrap-datepicker.zh-CN.min.js"></script>
    <script th:inline="javascript">
        // 设置百度地图API密钥
        window.BMAP_KEY = /*[[${@baiduMapConfig.apiKey}]]*/ '';

        let mapComponent;

        // 初始化地图
        document.addEventListener('DOMContentLoaded', async function() {
            try {
                mapComponent = new BaiduMapComponent('mapContainer', {
                    onLocationSelected: function(location) {
                        console.log('选择的位置:', location);
                        // 填充地址信息
                        const fullAddress = `${location.province}${location.city}${location.district}${location.street}${location.streetNumber}`;
                        document.getElementById('searchAddress').value = fullAddress;
                        document.getElementById('detailAddress').value = fullAddress;
                        document.getElementById('latitude').value = location.latitude;
                        document.getElementById('longitude').value = location.longitude;
                    },
                    onMapInitialized: function(map) {
                        console.log('地图初始化成功');
                    }
                });
                
                await mapComponent.init();
            } catch (error) {
                console.error('地图初始化失败:', error);
                alert('地图加载失败，请刷新页面重试');
            }
        });

        // 搜索地址
        function searchLocation() {
            const keyword = document.getElementById('searchAddress').value.trim();
            if (!keyword) {
                alert('请输入要搜索的地址');
                return;
            }
            mapComponent.searchAddress(keyword).catch(error => {
                console.error('搜索地址失败:', error);
                alert('搜索地址失败，请重试');
            });
        }

        // 初始化日期选择器
        $(document).ready(function() {
            $('#appointmentDate').datepicker({
                format: 'yyyy-mm-dd',
                startDate: new Date(),
                endDate: '+7d',
                autoclose: true,
                language: 'zh-CN',
                todayHighlight: true
            });
            
            // 只显示第一步
            document.querySelectorAll('.step-content').forEach(content => {
                content.style.display = 'none';
            });
            document.getElementById('step1-content').style.display = 'block';
        });

        let selectedWasteType = null;

        function selectWasteType(element, type) {
            // 移除其他卡片的选中状态
            document.querySelectorAll('.waste-type-card').forEach(card => {
                card.classList.remove('selected');
            });
            // 添加当前卡片的选中状态
            element.classList.add('selected');
            // 保存选中的类型
            selectedWasteType = type;
        }

        // 选择时间段
        function selectTimeSlot(element) {
            // 移除其他时间段的选中状态
            document.querySelectorAll('.time-slot').forEach(slot => {
                slot.classList.remove('selected');
            });
            // 添加当前时间段的选中状态
            element.classList.add('selected');
        }

        // 步骤切换函数
        function nextStep(currentStep) {
            if (!validateStep(currentStep)) {
                return;
            }
            
            // 隐藏当前步骤内容
            document.getElementById(`step${currentStep}-content`).style.display = 'none';
            // 显示下一步内容
            document.getElementById(`step${currentStep + 1}-content`).style.display = 'block';
            
            // 更新步骤指示器
            document.getElementById(`step${currentStep}`).classList.remove('active');
            document.getElementById(`step${currentStep + 1}`).classList.add('active');
            
            // 如果是最后一步，更新确认信息
            if (currentStep === 3) {
                updateConfirmInfo();
            }
        }

        function prevStep(currentStep) {
            // 隐藏当前步骤内容
            document.getElementById(`step${currentStep}-content`).style.display = 'none';
            // 显示上一步内容
            document.getElementById(`step${currentStep - 1}-content`).style.display = 'block';
            
            // 更新步骤指示器
            document.getElementById(`step${currentStep}`).classList.remove('active');
            document.getElementById(`step${currentStep - 1}`).classList.add('active');
        }

        function validateStep(step) {
            switch (step) {
                case 1:
                    // 验证地址信息
                    const address = document.getElementById('detailAddress').value;
                    const contactName = document.getElementById('contactName').value;
                    const contactPhone = document.getElementById('contactPhone').value;
                    const latitude = document.getElementById('latitude').value;
                    const longitude = document.getElementById('longitude').value;

                    if (!address) {
                        alert('请输入详细地址');
                        return false;
                    }
                    if (!contactName) {
                        alert('请输入联系人姓名');
                        return false;
                    }
                    if (!contactPhone) {
                        alert('请输入联系电话');
                        return false;
                    }
                    if (!latitude || !longitude) {
                        alert('请在地图上选择具体位置');
                        return false;
                    }
                    return true;

                case 2:
                    // 验证物品信息
                    if (!selectedWasteType) {
                        alert('请选择回收物品类型');
                        return false;
                    }
                    const weight = document.getElementById('estimatedWeight').value;
                    if (!weight || weight <= 0) {
                        alert('请输入有效的预估重量');
                        return false;
                    }
                    return true;

                case 3:
                    // 验证预约时间
                    const appointmentDate = document.getElementById('appointmentDate').value;
                    const selectedTimeSlot = document.querySelector('.time-slot.selected');
                    if (!appointmentDate || !selectedTimeSlot) {
                        alert('请选择预约日期和时间段');
                        return false;
                    }
                    return true;

                default:
                    return true;
            }
        }

        function updateConfirmInfo() {
            document.getElementById('confirm-address').textContent = document.getElementById('detailAddress').value;
            document.getElementById('confirm-contact').textContent = document.getElementById('contactName').value;
            document.getElementById('confirm-phone').textContent = document.getElementById('contactPhone').value;
            document.getElementById('confirm-type').textContent = getWasteTypeName(selectedWasteType);
            document.getElementById('confirm-weight').textContent = document.getElementById('estimatedWeight').value;
            
            const appointmentDate = document.getElementById('appointmentDate').value;
            const timeSlot = document.querySelector('.time-slot.selected').getAttribute('data-time');
            document.getElementById('confirm-time').textContent = `${appointmentDate} ${timeSlot}`;
        }

        function getWasteTypeName(type) {
            const typeMap = {
                'PAPER': '废纸',
                'PLASTIC': '塑料',
                'METAL': '金属',
                'APPLIANCE': '电器'
            };
            return typeMap[type] || type;
        }

        // 提交订单
        function submitOrder(event) {
            event.preventDefault();
            
            // 获取表单数据
            const formData = {
                address: document.getElementById('detailAddress').value,
                latitude: parseFloat(document.getElementById('latitude').value),
                longitude: parseFloat(document.getElementById('longitude').value),
                contactName: document.getElementById('contactName').value,
                contactPhone: document.getElementById('contactPhone').value,
                itemType: selectedWasteType,
                estimatedWeight: parseFloat(document.getElementById('estimatedWeight').value),
                appointmentTime: formatAppointmentTime(
                    document.getElementById('appointmentDate').value,
                    document.querySelector('.time-slot.selected').getAttribute('data-time')
                ),
                saveAddress: document.getElementById('saveAddress').checked
            };

            // 发送请求
            fetch('/api/orders/create', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('订单创建失败');
                }
                return response.json();
            })
            .then(data => {
                alert('订单创建成功！');
                window.location.href = '/orders/list';
            })
            .catch(error => {
                console.error('Error:', error);
                alert('订单创建失败：' + error.message);
            });

            return false;
        }

        function formatAppointmentTime(date, timeSlot) {
            // 将日期和时间段转换为完整的日期时间字符串
            const [startTime] = timeSlot.split('-');
            const [hours, minutes] = startTime.split(':');
            const appointmentDate = new Date(date);
            appointmentDate.setHours(parseInt(hours), parseInt(minutes), 0);
            return appointmentDate.toISOString();
        }

        // 加载保存的地址
        function loadSavedAddress(addressId) {
            if (!addressId) return;
            
            fetch(`/api/address/${addressId}`)
                .then(response => response.json())
                .then(address => {
                    document.getElementById('searchAddress').value = address.address;
                    document.getElementById('detailAddress').value = address.address;
                    document.getElementById('contactName').value = address.contactName;
                    document.getElementById('contactPhone').value = address.contactPhone;
                    document.getElementById('latitude').value = address.latitude;
                    document.getElementById('longitude').value = address.longitude;
                    
                    // 在地图上标记位置
                    const point = new BMapGL.Point(address.longitude, address.latitude);
                    mapComponent.updateLocation(point);
                })
                .catch(error => {
                    console.error('加载地址失败:', error);
                    alert('加载地址失败，请重试');
                });
        }
    </script>
</body>
</html> 